package kitrobot.com.bed.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import kitrobot.com.bed.CountDownUtil;
import kitrobot.com.bed.Service.IdentifyingService;
import kitrobot.com.bed.Service.LoginService;
import kitrobot.com.wechat_bottom_navigation.R;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_phone;
    private EditText et_psw;
    private EditText et_yan;
    private TextView tv_res;
    private TextView tv_gyan;
    private Context mContext;
    private int countSeconds = 60;
    private Handler mCountHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (countSeconds > 0) {
                --countSeconds;
                tv_gyan.setText("(" + countSeconds + ")后获取验证码");
                mCountHandler.sendEmptyMessageDelayed(0, 1000);
            } else {
                countSeconds = 60;
                tv_gyan.setText("请重新获取验证码");
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);
        et_phone= (EditText) findViewById(R.id.et_ltel);
        et_psw= (EditText) findViewById(R.id.et_lpass);
        et_yan= (EditText) findViewById(R.id.et_yan);
        tv_res= (TextView) findViewById(R.id.tv_res);
        tv_gyan= (TextView) findViewById(R.id.tv_gyan);
    }
    //获取验证码
    public void Yanzheng(View view) {
        final String phone=et_phone.getText().toString().trim();
        String a= String.valueOf(isMobileNO( phone));
        if (phone.length()==0){
            Toast.makeText(LoginActivity.this,"手机号码不能为空！",Toast.LENGTH_LONG).show();
        }
        else if(a.equals("false")||phone.length()<11){
            Toast.makeText(LoginActivity.this,"请输入正确的手机号码！",Toast.LENGTH_LONG).show();
        }
        else {
            new Thread(){
                public void run(){
                    final String result= IdentifyingService.IdentifyingByClientPost(phone);
                    if (result!=null){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Toast.makeText(LoginActivity.this,result,Toast.LENGTH_LONG).show();

                            }
                        });
                    }
                    else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this,"请求失败",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                };

            }.start();
            Jishi();
        }
    }
    //计时60秒
    public void Jishi(){
        new CountDownUtil(tv_gyan)

                .setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            final String phone=et_phone.getText().toString().trim();
                                            String a= String.valueOf(isMobileNO( phone));
                                            if (phone.length()==0){
                                                Toast.makeText(LoginActivity.this,"手机号码不能为空！",Toast.LENGTH_LONG).show();
                                            }
                                            else if(a.equals("false")||phone.length()<11){
                                                Toast.makeText(LoginActivity.this,"请输入正确的手机号码！",Toast.LENGTH_LONG).show();
                                            }
                                            else {
                                                new Thread(){
                                                    public void run(){
                                                        final String result= IdentifyingService.IdentifyingByClientPost(phone);
                                                        if (result!=null){
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    Toast.makeText(LoginActivity.this,result,Toast.LENGTH_LONG).show();
                                                                }
                                                            });
                                                        }
                                                        else{
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    Toast.makeText(LoginActivity.this,"请求失败",Toast.LENGTH_LONG).show();
                                                                }
                                                            });
                                                        }
                                                    };

                                                }.start();
                                                Jishi();
                                            }
                                        }
                                    }
                )
                .setCountDownMillis(60_000L)//倒计时60000ms
                .setCountDownColor(android.R.color.holo_blue_light,android.R.color.darker_gray)//不同状态字体颜色
                .start();
    }
    //获取信息进行登录
    public void Loginto(View view) {
        final String phone=et_phone.getText().toString().trim();
        final String password=et_psw.getText().toString().trim();
        final String code=et_yan.getText().toString().trim();
        String a= String.valueOf(isMobileNO( phone));
        if (phone.length()==0){
            Toast.makeText(LoginActivity.this,"手机号码不能为空！",Toast.LENGTH_LONG).show();
        }
        else if(a.equals("false")||phone.length()<11){
            Toast.makeText(LoginActivity.this,"请输入正确的手机号码！",Toast.LENGTH_LONG).show();
        }
        else if(password.length()==0){
            Toast.makeText(LoginActivity.this,"密码不能为空！",Toast.LENGTH_LONG).show();
        }
        else if(password.length()<6){
            Toast.makeText(LoginActivity.this,"密码不能小于6位！",Toast.LENGTH_LONG).show();
        }
        else if(code.length()==0){
            Toast.makeText(LoginActivity.this,"请输入验证码！",Toast.LENGTH_LONG).show();
        }
        else {
            new Thread(){
                public void run(){
                    final String result= LoginService.LoginByClientPost(phone,password,code);
                    if (result!=null){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String name=null;
                                String id=null;
                                String phone=null;
                                String token=null;
                                String errno=null;
                                String type=null;
                                Toast.makeText(LoginActivity.this,result,Toast.LENGTH_LONG).show();
                                try {
                                    //JSON字符串

                                    //根据JSON字符串 获得JSON object对象
                                    JSONObject jsonObject = new JSONObject(result);
                                    //根据key 获取相应的value
                                    JSONObject data=jsonObject.getJSONObject("data");
                                    errno=jsonObject.getString("errno");
                                    Toast.makeText(LoginActivity.this,errno,Toast.LENGTH_LONG).show();
                                    if(errno.equals("0")){
                                        name = data.getString("name");
                                        id = data.getString("id");
                                        phone=data.getString("phone");
                                        token=data.getString("token");
                                        type=data.getString("type");
                                        System.out.println("id="+id);
                                        System.out.println("名字="+name);
                                        System.out.println("手机="+phone);
                                        System.out.println("token="+token);
                                        System.out.println("类型="+type);
                                        SharedPreferences sp = getSharedPreferences("loginToken", 0);
                                        SharedPreferences.Editor editor = sp.edit();
                                        editor.putString("id",id);
                                        editor.putString("name",name);
                                        editor.putString("phone",phone);
                                        editor.putString("token",token);
                                        editor.putString("type",type);
                                        editor.putString("password",password);
                                        editor.commit();
                                        Intent i = new Intent(LoginActivity.this,MainActivity.class);
                                        startActivity(i);
                                        finish();
                                    }
                                    else {
                                        Toast.makeText(LoginActivity.this,"该手机号未注册",Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                        });
                    }
                    else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(LoginActivity.this,"请求失败",Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                };

            }.start();

        }
    }
    //使用正则表达式判断
    public static boolean isMobileNO(String mobiles) {
        //"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "13\\d{9}|14[57]\\d{8}|15[012356789]\\d{8}|18[01256789]\\d{8}|17[0678]\\d{8}"; ;
        if (TextUtils.isEmpty(mobiles)) return false ;
        else return mobiles.matches( telRegex ) ;
    }
    //获取验证码信息,进行计时操作
    private void startCountBack() {
        ((Activity) mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_gyan.setText(countSeconds + "");
                mCountHandler.sendEmptyMessage(0);
            }
        });
    }
    public void login(View view){
        String phone=et_phone.getText().toString().trim();
        String psw=et_psw.getText().toString().trim();
        String yan=et_yan.getText().toString().trim();
        if (phone.length() == 0){
            tv_res.setText("手机号不能为空！");
            System.out.print(tv_res);
        }
       else if (psw.length() == 0){
            tv_res.setText("密码不能为空！");
            System.out.print(tv_res);
        }
        else if (yan.length() == 0){
            tv_res.setText("验证码不能为空！");
            System.out.print(tv_res);
        }
       else {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClass(this, MajorActivity.class);
            startActivity(intent);
        }
    }
    public void Registe(View view){
        Intent intent=new Intent(this,RegisteActivity.class);
        startActivity(intent);
    }
    public void Forget(View view){
        String phone=et_phone.getText().toString().trim();
        Intent intent=new Intent(this,ForgetActivity.class);
        intent.putExtra("phone",phone);
        startActivity(intent);
    }
    @Override
    public void onClick(View view) {

    }
}
